package com.logistic.server.controller;


import com.logistic.server.common.constant.Constants;
import com.logistic.server.common.utils.FileUtils;
import com.logistic.server.entity.common.Result;
import com.logistic.server.entity.common.ResultGenerator;
import com.logistic.server.entity.common.UploadFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
import java.util.Objects;

/**
 * 文件接口
 * @author swen
 */
@Api(value = "文件接口", tags = {"文件接口"})
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadFileController {

    /**
     * 图片本地路径
     */
    @Value("${spring.web.resources.static-locations}")
    private String path;

    /**
     * 上传图片
     * @param file 文件
     * @return 结果
     */
    @ApiOperation(value = "文件上传接口", notes = "文件上传接口")
    @PostMapping(value = "/file", headers = "content-type=multipart/form-data")
    public Result<?> file(@ApiParam(value = "文件", required = true) MultipartFile file) {
        try {
            if(!file.isEmpty()){
                if(!Objects.requireNonNull(file.getContentType()).contains("image")){
                    return ResultGenerator.genFailResult("上传文件类型只可以是图片");
                }
                UploadFile uploadFile = UploadFile.builder()
                        .fileName(file.getOriginalFilename())
                        .filePath(Constants.UPLOAD_PATH + FileUtils.uploadFile(file, path))
                        .fileSize((int)file.getSize())
                        .fileType(FileUtils.getFileType(file.getOriginalFilename()))
                        .createDate(new Date())
                        .build();
                //返回图片url
                return ResultGenerator.genSuccessResult(uploadFile);
            }else{
                return ResultGenerator.genFailResult("图片不可以是空的");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("上传图片发生异常{}", e.getMessage());
            return  ResultGenerator.genFailResult("上传图片发生异常");
        }
    }
}
